package com.example.yrdev.ordering_system.Demo;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.Bundle;

import com.example.yrdev.ordering_system.Common.CommonActivity;
import com.example.yrdev.ordering_system.R;
import com.example.yrdev.ordering_system.Utils.GlobalFunction;

import android.nfc.NfcAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import com.dhF9.dhF9Jni;
/**
 * Created by yrdev on 9/2/16.
 */
//@EActivity(R.layout.test_activity_layout)

public class TestActivity extends CommonActivity {
  @InjectView(R.id.promt)
    TextView promt;



    String pwdData;//读卡密码

    String data;
    RadioGroup rg_operate, rg02_pwd;
    EditText writeData;


    int operate = 0;
    int pwd = 0;
    //private CheckBox mWriteData;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    //private PendingIntent pi = null;
    private IntentFilter tagDetected = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity_layout);
        ButterKnife.inject(this);
       setBarTitle("测试");
        initView();

        calcPass();

    }

    public void calcPass(){

    }

    public void initView(){
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        init_NFC();
        mPendingIntent =
                PendingIntent.getActivity(this, 0, new Intent(this,
                        getClass()), 0);

        String temp = "0";
        temp = bytesToHexString(MifareClassic.KEY_DEFAULT);
        pwdData=temp.toUpperCase();


    }
    private void init_NFC() {
        // 初始化PendingIntent，当有NFC设备连接上的时候，就交给当前Activity处理

        // 新建IntentFilter，使用的是第二种的过滤机制
        tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mNfcAdapter != null) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);

            GlobalFunction.printText("tag", "start processing");
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(this.getIntent()
                    .getAction())) {
                // 注意这个if中的代码几乎不会进来，因为刚刚在上一行代码开启了监听NFC连接，下一行代码马上就收到了NFC连接的intent，这种几率很小
                // 处理该intent
                processIntent(this.getIntent());

                //Toast.makeText(this, "get action after startNFC_Listener", Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        processIntent(intent);

    }

    public void processIntent(Intent intent) {
        Tag tag = intent.getParcelableExtra(mNfcAdapter.EXTRA_TAG);
        String[] techList = tag.getTechList();
        byte[] ID = new byte[20];

        //data = tag.toString();
        ID = tag.getId();

        pwdData=bytesToHexString(dhF9Jni.calculatePass(ID)).toUpperCase();

        data = "UID:\n" + bytesToHexString(ID);
        data += "\n数据格式:";
        for (String tech : techList) {
            data += "\n" + tech;
        }
        data += "\n\n";
        if (operate == 0) // 读M1卡
        {
            data += readM1Tag(tag,6);
        } else if (operate == 1) {
            data += writeTag(tag);
        }
GlobalFunction.printText("tag",data);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                promt.setText(data);
            }
        });

        return;
    }
    @Override
    public void onPause() {
        super.onPause();
        if (mNfcAdapter != null) {
            //mNfcAdapter.disableForegroundDispatch(this);
            stopNFC_Listener();
        }

    }
    private void stopNFC_Listener() {
        // 停止监听NFC设备是否连接
        mNfcAdapter.disableForegroundDispatch(this);
    }

    // 字符序列转换为16进制字符串
    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }
    // 16进制字符转String
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }
    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }


    public String readM1Tag(Tag tag,Integer sector) {

        MifareClassic mfc = MifareClassic.get(tag);
//        for (String tech : tag.getTechList()) {
//            System.out.println(tech);
//        }
        boolean auth = false;
        // 读取TAG

        try {
            GlobalFunction.printText("tag","read successs" + ":"+pwdData);
            String metaInfo = "";
            //Enable I/O operations to the tag from this TagTechnology object.
            mfc.connect();
            int type = mfc.getType();// 获取TAG的类型
            int sectorCount = mfc.getSectorCount();// 获取TAG中包含的扇区数
            String typeS = "";
            switch (type) {
                case MifareClassic.TYPE_CLASSIC:
                    typeS = "TYPE_CLASSIC";
                    break;
                case MifareClassic.TYPE_PLUS:
                    typeS = "TYPE_PLUS";
                    break;
                case MifareClassic.TYPE_PRO:
                    typeS = "TYPE_PRO";
                    break;
                case MifareClassic.TYPE_UNKNOWN:
                    typeS = "TYPE_UNKNOWN";
                    break;
            }
            metaInfo += "卡片类型：" + typeS + "\n共" + sectorCount + "个扇区\n共" + mfc.getBlockCount() + "个块\n存储空间: " + mfc.getSize()
                    + "B\n";
            for (int j = 0; j < sectorCount; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j, hexStringToByte(pwdData));
                if (j==sector){
                    int bCount;
                    int bIndex;
                    if (auth) {
                        metaInfo += "Sector " + j + ":验证成功\n";
                        // 读取扇区中的块
                        bCount = mfc.getBlockCountInSector(j);
                        bIndex = mfc.sectorToBlock(j);
                        for (int i = 0; i < bCount; i++) {
                            byte[] data = mfc.readBlock(bIndex);
                            metaInfo += "Block " + bIndex + " : "
                                    + bytesToHexString(data) + "\n";
                            bIndex++;
                        }
                    } else {
                        metaInfo += "Sector " + j + ":验证失败\n";
                    }
                }
            }
            GlobalFunction.printText("tag",metaInfo);
            return metaInfo;
        } catch (Exception e) {
            GlobalFunction.ToastAlert(this, e.getMessage());
            //Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } finally {
            if (mfc != null) {
                try {
                    mfc.close();
                } catch (IOException e) {
                    GlobalFunction.ToastAlert(this, e.getMessage());
                }
            }
        }
        return null;
    }


    public String writeTag(Tag tag) {

        String metaInfo = "";

        MifareClassic mfc = MifareClassic.get(tag);

        try {
            mfc.connect();
            int sectorCount = mfc.getSectorCount();// 获取TAG中包含的扇区数
            boolean auth = false;
            byte temp[] = new byte[16];
            for(int k = 0; k < temp.length;k++ )
            {
                temp[k]= (byte) Integer.parseInt(writeData.getText().toString());
            }
//            short sectorAddress = 1;
//            //auth = mfc.authenticateSectorWithKeyA(sectorAddress, MifareClassic.KEY_NFC_FORUM);
//            auth = mfc.authenticateSectorWithKeyA(j, hexStringToByte(pwdData.getText().toString()));
//            if (auth) {
//                // the last block of the sector is used for KeyA and KeyB cannot be overwritted
//                mfc.writeBlock(4, "1313838438000000".getBytes());
//                mfc.writeBlock(5, "1322676888000000".getBytes());
//                mfc.close();
            // Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();
//            }

            for (int j = 0; j < sectorCount; j++) {
                //Authenticate a sector with key A.
                auth = mfc.authenticateSectorWithKeyA(j, hexStringToByte(pwdData));
                int bCount;
                int bIndex;
                if (auth) {
                    metaInfo += "Sector " + j + ":验证成功\n";
                    // 读取扇区中的块
                    bCount = mfc.getBlockCountInSector(j);
                    bIndex = mfc.sectorToBlock(j);
                    for (int i = 0; i < bCount; i++) {
                        int block = 4*j+i;
                        if ( block == 0 || block%4 == 3){
                            continue;
                        }
                        mfc.writeBlock(block, temp);
                        bIndex++;
                    }
                } else {
                    metaInfo += "Sector " + j + ":验证失败\n";
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                mfc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return metaInfo;
    }


}
